package com.bruce.pattern.structural.proxy.dynamicproxy;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created by bruce on 2018/11/9 21:12
 */
@Slf4j
public class CglibDBQueryInterceptor implements MethodInterceptor {
    private DBQueryI target;

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {

        //不能保证DBQueryImpl对象是单例的

        //表示调用原始类的被拦截到的方法,被代理的类必须是普通类,不能是接口,或抽象类
        //Object o1 = methodProxy.invokeSuper(obj, args);
        //log.info("调用原始类的被拦截到的方法" + o1);

        if (target == null) {
            target = new DBQueryImpl();
        }
        return method.invoke(target, args);
    }
}
